package com.windows;

import com.entity.Good;
import com.util.GoodUtil;
import com.util.LogUtil;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

/**
 * 超市管理页面
 * 功能：商品销售，商品添加，商品查询，商品修改，商品删除，商品统计
 * 添加  关于、退出
 *
 * @author Yasin
 *
 */
public class Home extends JFrame{

    private JPanel contentPane;                      //窗体容器面板
    private JTabbedPane tabbedPane;                  //选项卡面板
    private JButton button1;                         //商品管理按钮
    private JButton button2;                         //管理记录按钮
    private JButton button3;                         //关于按钮
    private JButton button4;                         //退出按钮
    private JButton button5;                         //查找按钮

    private JTable[] table = new JTable[4];          //数据表格数组
    private String temp;                             //当前选项卡名称
    private int index;                               //当前选项卡编号

    private JPopupMenu popupMenu;                    //鼠标弹出菜单
    private JMenuItem items[];                       //弹出菜单内容

    private int row;                                 //数据表单选中行

    public static void main(String[] args) {
        new Home();
    }

    public Home() {

        setTitle("超市商品管理系统");
        setSize(1000, 800);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        tabbedPane = new JTabbedPane();              //实例选项卡面板

        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));

        contentPane.add(tabbedPane,BorderLayout.CENTER);
        setContentPane(contentPane);



        leftButton();                                        //左侧按钮初始化


        addListener();                                       //左侧按钮添加监听


        setVisible(true);
    }


    public void mouse() {                                    //鼠标事件匿名内部类

        popupMenu = new JPopupMenu();
        items = new JMenuItem[5];
        items[0] = new JMenuItem("刷新");
        items[1] = new JMenuItem("商品销售");
        items[2] = new JMenuItem("商品删除");
        items[3] = new JMenuItem("商品添加");
        items[4] = new JMenuItem("商品修改");



        for(JMenuItem item :items)
            popupMenu.add(item);

        MouseAdapter m = new MouseAdapter() {         //添加一个匿名内部类

            public void mouseReleased(MouseEvent e) {

                if(e.isPopupTrigger())

                    popupMenu.show(e.getComponent(),e.getX(),e.getY());

            }


            public void mouseClicked(MouseEvent e) {



                Point mousepoint;
                temp =
                        tabbedPane.getTitleAt(tabbedPane.getSelectedIndex()); mousepoint
                        =e.getPoint();     //获取鼠标位置

                temp = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());

                if("食品".equals(temp)) {

                    index = 0;

                }else if("化妆品".equals(temp)){

                    index = 1;

                }else if("日用品".equals(temp)) {

                    index = 2;

                }else if("饮料".equals(temp)) {


                    index = 3;
                }

                row = table[index].rowAtPoint(mousepoint); //此方法返回行号
                table[index].setRowSelectionInterval(row,row); //设置为选中此行



            }
        };

        //刷新按钮
        items[0].addActionListener(new ActionListener() {


            public void actionPerformed(ActionEvent e) {

                try {
                    tabbedPane();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                tabbedPane.setSelectedIndex(index);
            }
        });

        //商品销售
        items[1].addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                new SellGood(temp,(String)table[index].getValueAt(row, 0),Integer.valueOf((String)table[index].getValueAt(row, 2)));
                try {
                    tabbedPane();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                tabbedPane.setSelectedIndex(index);
            }
        });


        //删除操作
        items[2].addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                try {

                    GoodUtil.deleteGood((String)table[index].getValueAt(row, 0));
                    LogUtil.addlog("删除"+(String)table[index].getValueAt(row, 0)+"-->"+"成功");
                    JOptionPane.showMessageDialog(null, "删除成功", "删除结果",JOptionPane.PLAIN_MESSAGE);
                    tabbedPane();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                tabbedPane.setSelectedIndex(index);
            }
        });

        //商品添加
        items[3].addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                new AddGood(index);
                try {
                    tabbedPane();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                tabbedPane.setSelectedIndex(index);
            }
        });

        //商品修改
        items[4].addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                new UpdateGood(temp,(String)table[index].getValueAt(row, 0));

                try {
                    tabbedPane();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                tabbedPane.setSelectedIndex(index);
            }
        });


        for(JTable j : table) {

            j.addMouseListener(m);
            j.addMouseMotionListener(m);
        }
    }



    private void leftButton() {                              //左侧按钮初始化实现

        JPanel panel = new JPanel();
        contentPane.add(panel,BorderLayout.WEST);
        panel.setLayout(new GridLayout(8, 1, 0, 5));

        JLabel label = new JLabel("功能选择");                 //添加功能选择标签
        label.setFont(new Font("宋体",Font.PLAIN,20));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setBackground(Color.YELLOW);
        panel.add(label);

        button1 = new JButton("商品管理");
        button1.setFont(new Font("宋体",Font.PLAIN,20));
        panel.add(button1);

        button2 = new JButton("管理记录");
        button2.setFont(new Font("宋体",Font.PLAIN,20));
        panel.add(button2);

        button3 = new JButton("关于");
        button3.setFont(new Font("宋体",Font.PLAIN,20));
        panel.add(button3);

        button4 = new JButton("退出");
        button4.setFont(new Font("宋体",Font.PLAIN,20));
        panel.add(button4);


    }





    public void addListener() {                                      //添加监听


        button1.addActionListener(new ActionListener() {             //商品管理按钮监听


            public void actionPerformed(ActionEvent e) {


                try {
                    tabbedPane();                                        //添加选项卡
                }catch (Exception a){
                    a.printStackTrace();
                }
            }
        });


        button2.addActionListener(new ActionListener() {             //管理记录按钮监听


            public void actionPerformed(ActionEvent e) {

                LogUtil.logList(tabbedPane);
            }
        });


        button3.addActionListener(new ActionListener() {             //关于按钮监听


            public void actionPerformed(ActionEvent e) {

                tabbedPane.removeAll();
                JTextArea text = new JTextArea();
                text.setFont(new Font("宋体",Font.BOLD,30));
                text.setEditable(false);
                text.setText("作者：姜彦昕、苏陆伟男\n禁止用于商业行为，详情请加QQ：879533618");

                tabbedPane.add(text,"关于");
            }
        });


        button4.addActionListener(new ActionListener() {             //退出按钮监听


            public void actionPerformed(ActionEvent e) {



                System.exit(0);
            }
        });






    }


    public void tabbedPane() throws Exception {                                        //选项卡初始化

        tabbedPane.removeAll();                                       //每次执行之前先清一遍面板，防止重复添加


        tabbedPane.addTab("食品", tabel("food"));


        tabbedPane.addTab("化妆品",tabel("cosmetics"));



        tabbedPane.addTab("日用品", tabel("necessities"));


        tabbedPane.addTab("饮料", tabel("drink"));

        mouse();


    }


    public JPanel tabel(String id) throws Exception {                                            //表格初始化

        JScrollPane scroll = null;
        java.util.List<Good> goodList = null;
        JPanel panel = new JPanel();

        panel.setLayout(new BorderLayout());


        String[] str = {"名称","价格","数量","生产厂家","品牌","其他"};
        String[][] strs = null;

        if("food".equals(id)) {

            goodList = GoodUtil.findFood().getGoods();
            strs = GoodUtil.packString(goodList).getStrings();

            if(strs == null) {
                strs =new String[1][6];
                for(int i = 0;i<6;i++) {
                    strs[0][i] = "空";
                }
            }

            table[0] = new JTable(strs,str) {

                public boolean isCellEditable(int row, int column) {
                    return false;

                };

            };
            table[0].setRowHeight(30);

            scroll = new JScrollPane(table[0]);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        }else if("cosmetics".equals(id)){

            goodList = GoodUtil.findCos().getGoods();
            strs= GoodUtil.packString(goodList).getStrings();
            if(strs == null) {
                strs =new String[1][6];
                for(int i = 0;i<6;i++) {
                    strs[0][i] = "空";
                }
            }

            table[1] = new JTable(strs,str) {

                public boolean isCellEditable(int row, int column) {
                    return false;

                };

            };
            table[1].setRowHeight(30);

            scroll = new JScrollPane(table[1]);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        }else if("necessities".equals(id)) {

            goodList = GoodUtil.findNess().getGoods();
            strs= GoodUtil.packString(goodList).getStrings();

            if(strs == null) {
                strs =new String[1][6];
                for(int i = 0;i<6;i++) {
                    strs[0][i] = "空";
                }
            }


            table[2] = new JTable(strs,str) {

                public boolean isCellEditable(int row, int column) {
                    return false;

                };

            };
            table[2].setRowHeight(30);

            scroll = new JScrollPane(table[2]);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        }else if("drink".equals(id)) {

            goodList = GoodUtil.findDrink().getGoods();
            strs= GoodUtil.packString(goodList).getStrings();

            if(strs == null) {
                strs =new String[1][6];
                for(int i = 0;i<6;i++) {
                    strs[0][i] = "空";
                }
            }

            table[3] = new JTable(strs,str) {

                public boolean isCellEditable(int row, int column) {
                    return false;

                };

            };
            table[3].setRowHeight(30);

            scroll = new JScrollPane(table[3]);
            scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        }



        panel.add(scroll);


        JPanel p = new JPanel();
        JLabel lab = new JLabel("商品查找");

        JTextField msg = new JTextField();
        msg.setColumns(20);

        button5 = new JButton("查找");

        button5.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tabbedPane.removeAll();
                JPanel panel = new JPanel();

                JTable table = null;
                String name = msg.getText();
                JScrollPane scroll = null;
                java.util.List<Good> goodList = null;


                panel.setLayout(new BorderLayout());


                String[] str = {"名称","价格","数量","生产厂家","品牌","其他"};
                String[][] strs = null;

                strs = GoodUtil.packString(GoodUtil.findByName(name).getGoods()).getStrings();

                if(strs == null) {
                    strs =new String[1][6];
                    for(int i = 0;i<6;i++) {
                        strs[0][i] = "空";
                    }
                }

                table = new JTable(strs,str) {

                    public boolean isCellEditable(int row, int column) {
                        return false;

                    };

                };
                table.setRowHeight(30);

                scroll = new JScrollPane(table);
                scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

                panel.add(scroll);
                tabbedPane.add(panel,"查找");

            }
        });

        p.add(lab);
        p.add(msg);
        p.add(button5);


        panel.add(p, BorderLayout.SOUTH);

        return panel;


    }



}
